package com.hammer.m3u8downloader;

import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.hammer.m3u8downloader.adapter.M3U8ManagerListAdapter;
import com.hammer.m3u8downloader.entity.M3U8DownloadItemEntity;
import com.hammer.m3u8downloader.util.LocalM3U8Manager;
import com.hammer.m3u8downloader.widget.MenuDialog;
import com.hammer.m3u8downloader.widget.SnackDialog;
import com.test.player.FuckPlayer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import jaygoo.library.m3u8downloader.M3U8Downloader;
import jaygoo.library.m3u8downloader.OnDeleteTaskListener;
import jaygoo.library.m3u8downloader.server.EncryptM3U8Server;

public class LocalM3U8Activity extends AppCompatActivity {
    private ListView listView;
    private M3U8ManagerListAdapter adapter;
    private List<M3U8DownloadItemEntity> downloadItemEntityList = new ArrayList<>();
    private SnackDialog snackDialog;
    private EncryptM3U8Server m3u8Server = new EncryptM3U8Server();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_local_m3u8);
        m3u8Server.execute();
        initView();
    }


    private void initView() {
        snackDialog = new SnackDialog(this);
        listView = findViewById(R.id.lv_download);
        downloadItemEntityList.addAll(LocalM3U8Manager.getInstance(getApplicationContext()).getTaskList("=2"));
        adapter = new M3U8ManagerListAdapter(this, R.layout.item_m3u8_download, listView, downloadItemEntityList);
        listView.setAdapter(adapter);
        adapter.setOnItemClickListener((position, itemEntity) -> showMenuDialog(itemEntity));
    }

    private void updateTaskList() {
        downloadItemEntityList.clear();
        downloadItemEntityList.addAll(LocalM3U8Manager.getInstance(getApplicationContext()).getTaskList("=2"));
        adapter.notifyDataSetChanged();
    }

    private void showMenuDialog(final M3U8DownloadItemEntity entity) {
        new MenuDialog(this)
                .setMenuTitle("选择操作方式")
                .addMenuItem(Arrays.asList("打开文件", "删除任务"))
                .setCallBack((dialogInterface, i) -> {
                    switch (i) {
                        case 0:
                            Log.e("taskFile", "uri: " + entity.getTaskFile());
                            String httpUrl = m3u8Server.createLocalHttpUrl(entity.getTaskFile());
                            Log.e("httpUrl", "uri: " + httpUrl);
                            new FuckPlayer(LocalM3U8Activity.this).setTitle(entity.getTaskName()).setUrl(httpUrl).islive(true).start();
                            break;
                        case 1:
                            new AlertDialog.Builder(LocalM3U8Activity.this, R.style.MyAlertDialogStyle)
                                    .setTitle("提示")
                                    .setMessage("是否确认删除当前任务：" + entity.getTaskName())
                                    .setPositiveButton("彻底删除", (dialogInterface1, i1) -> {
                                        snackDialog.setTitle("删除任务").setSubTitle("正在删除").show();
                                        deleteTask(entity.getTaskUrl());
                                    })
                                    .setNegativeButton("保留缓存", (dialogInterface12, i12) -> {
                                        M3U8Downloader.getInstance().cancel(entity.getTaskUrl());
                                        LocalM3U8Manager.getInstance(LocalM3U8Activity.this).deleteTask(entity.getTaskUrl());
                                        updateTaskList();
                                        showWarningDialog("已删除下载记录，下次下载相同任务可以断点续传");

                                    })
                                    .setNeutralButton("取消", (dialogInterface13, i13) -> {

                                    })
                                    .show();
                            break;
                        case 2:

                            break;
                    }
                })
                .show();
    }

    private void deleteTask(final String url) {
        M3U8Downloader.getInstance().cancelAndDelete(url, new OnDeleteTaskListener() {
            @Override
            public void onStart() {
                runOnUiThread(() -> snackDialog.setSubTitle("开始删除..."));
            }

            @Override
            public void onSuccess() {
                runOnUiThread(() -> {
                    LocalM3U8Manager.getInstance(getApplicationContext()).deleteTask(url);
                    updateTaskList();
                    showWarningDialog("删除成功");
                    snackDialog.dismiss();
                });

            }

            @Override
            public void onFail() {
                runOnUiThread(() -> {
                    showWarningDialog("删除失败，请重试");
                    snackDialog.dismiss();
                });
            }

            @Override
            public void onError(final Throwable errorMsg) {
                runOnUiThread(() -> {
                    showWarningDialog("删除错误：" + errorMsg.toString());
                    snackDialog.dismiss();
                });

            }
        });
    }

    private void showWarningDialog(final String text) {
        new AlertDialog.Builder(this, R.style.MyAlertDialogStyle).setTitle("提示").setMessage(text).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        m3u8Server.decrypt();
        updateTaskList();
    }

    @Override
    protected void onPause() {
        super.onPause();
        m3u8Server.encrypt();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        m3u8Server.finish();
    }
}
